import React from 'react';
import { message } from 'antd';
import { TableMethods, SaveState } from '@/common/Hoc/data';
import PubSub from 'pubsub-js';

export const SimpleSaveHoc: any = (methods: TableMethods) => (
  Component: React.ComponentType<any>,
) => {
  return class extends React.Component<any, SaveState> {
    constructor(props: any) {
      super(props);

      this.state = {
        loading: false,
      };
    }

    componentDidMount(): void {}

    /* 保存数据 */
    saveData = (form: any, currentData: {}, filterData?: Function, customerData?: {}) => {
      if (methods.getSave) {
        form.validateFields((err: any, fieldsValue: any) => {
          if (err) {
            return;
          }
          let keys = Object.keys(fieldsValue);
          if (keys) {
            keys.forEach(key => {
              currentData[key] = fieldsValue[key];
            });
          }
          if (filterData) {
            filterData(currentData);
          }
          let data = { ...currentData };
          if (customerData) {
            data = { ...currentData, ...customerData };
          }
          this.save(data);
        });
      }
    };

    /*模态框隐藏*/
    closeModel = (func: Function) => {
      func(false);
    };

    save = (values: any) => {
      this.setState({
        loading: true,
      });

      if (!methods.getSave) {
        return;
      }

      methods
        .getSave(values)
        .then((res: any) => {
          if (res.status === 0) {
            this.props.handleModalVisible(false);
            PubSub.publish('refresh');
          } else {
            message.error(res.msg);
          }
          this.setState({
            loading: false,
          });
        })
        .catch((res: any) => {
          this.setState({
            loading: false,
          });
        });
    };

    render() {
      const { loading } = this.state;

      return <Component {...this.props} tableLoading={loading} saveData={this.saveData} />;
    }
  };
};
